package com.sy.core.util;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;

public class NumUtils {
	/**
	 * 把数字转换成money保留一位小数，向上取整
	 * @param amount
	 */
	public static String parseMoneyUp(String amount){
		if(amount.substring(amount.indexOf(".")).length()>2){
			String str = amount.substring(amount.indexOf(".")+2,amount.indexOf(".")+3);
			System.out.println(str);
			if(Integer.parseInt(str)>0){
				String money = amount.substring(0,amount.indexOf(".")+2);
				amount = new BigDecimal(money).add(new BigDecimal("0.1")).toString();
			}
		}
		 BigDecimal bd  = new BigDecimal(amount);
		 NumberFormat nf = new DecimalFormat(",##0.0");
		 String a = nf.format(bd);
		 return a;
	}
	
	//把数字转换成money
	public static String parseMoney(String amount){
		 BigDecimal bd  = new BigDecimal(amount);
		 NumberFormat nf = new DecimalFormat(",##0.00");
		 String a = nf.format(bd);
		 return a;
	}
	
	//把数字转换成money取整
		public static String parseMoneyRoundNumbers(String amount){
			 BigDecimal bd  = new BigDecimal(amount);
			 NumberFormat nf = new DecimalFormat(",##0");
			 String a = nf.format(bd);
			 return a;
		}
	
	/**
     * 保留两位小数，四舍五入的一个老土的方法
     * @param d
     * @return
     */
    public static double formatDouble(double d) {
    	double num = (double)Math.round(d*100)/100.00;
        return num;
    }
    

	/**
	 * BigDecimal的加法运算封装
	 * @param b1
	 * @param bn
	 * @return
	 */
   public static BigDecimal safeAdd(BigDecimal b1, BigDecimal... bn) {
       if (null == b1) {
           b1 = BigDecimal.ZERO;
       }
       if (null != bn) {
           for (BigDecimal b : bn) {
               b1 = b1.add(null == b ? BigDecimal.ZERO : b);
           }
       }
       return b1;
   }
    
    /**
     * 这个方法挺简单的。
     * DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. 
     * @param d
     * @return
     */
    public static String formatDouble2(double d) {
        DecimalFormat df = new DecimalFormat("0.00");
        
        return df.format(d);
    }

    public static void main(String[] args) {
    	/*String d = NumUtils.parseMoneyUp("4561.5245345");
    	System.out.println(d);*/
    	
    	BigDecimal a = NumUtils.safeAdd(new BigDecimal("2531.35"),new BigDecimal("0"),new BigDecimal("56.21"));
    	System.out.println(a.toString());
    	
    }
}
